<?php
/**
 * Created by JieHuiLong.
 * E-mail: jiehuilong@icloud.com
 * Date: 2016/8/16
 * Time: 16:00
 * 广告分组管理控制器
 */

namespace App\Http\Controllers\Admin;

use App\Models\DomainAttributes;
use Illuminate\Http\Request;

use App\Http\Controllers\Controller;
use App\Http\Requests\GroupCreateRequest;
use App\Http\Requests\GroupUpdateRequest;
use App\Models\Group;
use App\Models\GroupAttributes as GroupAttr;
use App\Models\Domain;
use App\Models\Templates;
use App\Models\DomainAttributes as DomainAttr;
use App\Models\Wechat;
use App\Models\WechatGroup;
use App\Models\CopyAccount;

use App\Models\Term;

use App\Models\AdminUser as User;
use Cache,Config,DB;

class CopyController extends Controller
{

    protected $fields = [
        'uid' => 1,
        'dated' => '',
        'gaccount' => '',
        'channel' => '',
        'domain' => '',
        'sum_copy' => 0,
        'consume' => 0,
        'client' => 0,
    ];

    /**
     * 根据requst 返回分组列表数据
     *
     * @return Json
     */
    public function __construct(Request $request)
    {
        $this->uid 		= auth()->user()->id;
        $this->username = auth()->user()->name;
    }
    public function index(Request $request)
    {

        $unDone = CopyAccount::where('consume','<>',0)->where('cp_cost',0)->get()->toArray();
        if(!empty($unDone)){
            foreach ($unDone as $key => $thisObj) {
            $map['dated'] = $thisObj['dated'];
            $map['gaccount'] = $thisObj['gaccount'];
            $cp_cost= round($thisObj['consume'] / $thisObj['sum_copy']);
            $thisObj = CopyAccount::find((int)$thisObj['id']);
            $thisObj->cp_cost= round($thisObj->consume / $thisObj->sum_copy);
            $thisObj->save();
        }
        }
        
        if ($request->ajax()) {
            $data 					= array();
            $data['draw'] 			= $request->get('draw');
            $start 					= $request->get('start');
            $length 				= $request->get('length');
            $order 					= $request->get('order');
            $columns 				= $request->get('columns');
            $search 				= $request->get('search');
            $search['value'] = trim($search['value']);
            $data['recordsTotal'] 	= CopyAccount::where(session('authAdminCondition'))->count();
            if (strlen($search['value']) > 0) {
                $data['recordsFiltered'] 	= CopyAccount::where(function ($query) use ($search) {
                    $query->where('dated', 'LIKE', '%' . $search['value'] . '%')
                        ->orWhere('gaccount', 'like', '%' . $search['value'] . '%')
                        ->orWhere('channel', 'like', '%' . $search['value'] . '%');
                })->where(session('authAdminCondition'))->count();
                $data['data'] 				= CopyAccount::where(function ($query) use ($search) {
                    $query->where('dated', 'LIKE', '%' . $search['value'] . '%')
                        ->orWhere('gaccount', 'like', '%' . $search['value'] . '%')
                        ->orWhere('channel', 'like', '%' . $search['value'] . '%');
                })->where(session('authAdminCondition'))
                    ->skip($start)->take($length)
                    ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                    ->get();
            } else {
                $data['recordsFiltered'] 	= $data['recordsTotal'];
                $data['data'] 				= CopyAccount::where(session('authAdminCondition'))
                    ->skip($start)->take($length)
                    ->orderBy($columns[$order[0]['column']]['data'], $order[0]['dir'])
                    ->get();
            }

            return response()->json($data);

        }

        return view('admin.copy.index');
    }



    /**
     * 向数据表新增一条记录
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(GroupCreateRequest $request)
    {
        $group 					= new Group();
        foreach (array_keys($this->fields) as $field) {
			if($field=='tpl_id'||$field=='template'||$field=='term_id'){
				$tpl_ids 		= $request->get($field);
				$str 			= "";
				foreach($tpl_ids as $tpl_id){
					$str 		.= $tpl_id.",";
				}
				$str 			= substr($str,0,strlen($str)-1); 
				$group->$field 	= $str;
				continue;
			}
            $group->$field 		= $request->get($field);
        }
        $checkId 				= Group::where(["title" => $group->title,"directory" => $group->directory, "uid" => $this->uid])->value('id');
        if ($checkId) {
            return back()->withErrors('添加失败！【分组名】不能重复，请您使用其他分组名');
        }
        $group->save();
        if($group->id){
            $item['uid'] 		= $this->uid;
            $item['username'] 	= $this->username;
            $item['gid'] 		= $group->id;
            $item['gname'] 		= $group->title;
            $item['type'] 		= '多行文本';
            $item['type_value'] = 'text';
            $item['created_at'] = date('Y-m-d H:i:s');
            $defaultAttr = array("顶部菜单","底部版权信息","统计代码");
            foreach ($defaultAttr as $key => $obj){
                $item['name'] 	= $obj;
                $item['call_tag'] 	= $obj;
                $data[] 		= $item;
            }
            if(!empty($data))GroupAttr::insert($data);
        }

		event(new \App\Events\userActionEvent('\App\Models\Group',$group->id, 1, '新增了分组['.$group->title.']' ));
        return redirect('/admin/group')->withSuccess('添加成功！');
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }
    public function batch(Request $request)
    {
        // if ($request) return redirect('/admin/copy')->withSuccess('更新失败！');
        dd('batch');
    }
    /**
     * 编辑数据
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $thisObj = CopyAccount::find((int)$id);
        if ($thisObj) {
            if (!$thisObj) return redirect('/admin/copy')->withErrors("找不到该记录!");
            foreach (array_keys($this->fields) as $field) {

                $data[$field] = old($field, $thisObj->$field);
            }
            $data['id'] = (int)$id;
            // dd($data);
            return view('admin.copy.edit', $data);
        }else{
            return view('admin.copy.batch');
        }
        
    }

    /**
     * 更新数据
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        
        if( !empty(trim($request->get('dated'))) ){
            $_source = trim($request->get('source'));
            $_dated = trim($request->get('dated'));
            if (empty($_dated)) return redirect('admin/copy/0/edit')->withErrors('更新失败，先选择更新时间！');
            var_dump($_dated);
            $_sorceArr = explode("\r\n",$_source);
            $accoutCostArr = $accoutCostArrList = [];
            foreach ($_sorceArr as $key => $objAcc) {
                $_obj = explode("\t",$objAcc);
                $accoutCostArr[$_obj[0]] = $_obj[1];
                $accoutCostArrList = array_merge($accoutCostArrList,$accoutCostArr);
                $accoutCostArr = [];
                
            }
            // dd($accoutCostArrList);
            foreach ($accoutCostArrList as $gaccount => $ac_cost) {
                $map['dated'] = $_dated;
                $map['gaccount'] = $gaccount;
                $thisObjArr = CopyAccount::where($map)->get();
                foreach ($thisObjArr as $thisKey => $thisObj) {
                    $cp_cost= round($thisObj->consume / $thisObj->sum_copy);
                    CopyAccount::where($map)->update(['consume'=>$ac_cost,'cp_cost'=>$cp_cost]);
                } 
            }
            return redirect('admin/copy')->withSuccess('更新成功！');
        }else{

            $thisObj = CopyAccount::find((int)$id);
            // foreach (array_keys($this->fields) as $field) {
            //     $thisObj->$field     =   $request->get($field);
            // }
            $thisObj->consume        =   $request->get('consume');
            $thisObj->client        =   $request->get('client');
            $thisObj->cp_cost = 0;
            $thisObj->rmb_cost = 0;
            if( $thisObj->consume ) $thisObj->cp_cost= round($thisObj->consume / $thisObj->sum_copy);
            if( $thisObj->client ) $thisObj->rmb_cost= round($thisObj->consume / $thisObj->client);
            $thisObj->save();
            return redirect('admin/copy')->withSuccess('更新成功！');
            // return redirect()->back()->withSuccess('更新成功！');    
        }

    }

    /**
     * 删除数据
     *
     * @param  int $id or string ids=>1,2,3,4,5,6
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        if(is_numeric($id)){
            $tag = User::find((int)$id);
            if ($tag) {
                $tag->delete();
            } else {
                return redirect()->back()->withErrors("删除失败");
            }
        }else{
            $idArr = explode(',',$id);
            User::whereIn('id',$idArr)->delete();
            if(!$recordRow){
                return redirect()->back()->withErrors("删除失败");
            }
        }
        return redirect()->back()->withSuccess("删除成功");
    }
	
}